<template>
  <div class="student">
    <el-card>
      <!-- 搜索 -->
      <div class="search">
        <el-form :inline="true">
          <el-form-item label="用户名：">
            <el-input v-model="params.userName" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="handleQuery">查询</el-button>
            <el-button :disabled="loading" @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleAdd">添加</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 列表 -->
      <el-table :data="tableData" style="width: 100%" :loading="loading" stripe>
        <el-table-column prop="id" label="id" width="70" />
        <el-table-column prop="userName" label="用户名" width="130" />
        <el-table-column prop="realName" label="真实姓名" width="130" />
        <el-table-column prop="sex" label="性别" width="70">
          <template #default="{ row }">
            {{ row.sex === 1 ? "男" : row.sex === 2 ? "女" : "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button type="warning" size="small" @click="handleToggleStatus(row)">
              {{ row.status === 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px">
        <el-pagination
          v-model:current-page="params.pageIndex"
          v-model:page-size="params.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import UserAPI, { type AdminParams, type UserType } from "@/api/system/user.api";
import { ElMessageBox, ElMessage } from "element-plus";

// 列表数据 & 状态
const tableData = ref<UserType[]>([]);
const total = ref(0);
const loading = ref(false);

// 查询参数（管理员 role 固定为 3，后端在 getAdminPage 中自动设置）
const params = ref<AdminParams>({
  userName: "",
  pageIndex: 1,
  pageSize: 10,
});

function getList() {
  loading.value = true;
  UserAPI.getAdminPage(params.value)
    .then((data: any) => {
      tableData.value = data.list || [];
      total.value = data.total || 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 事件
function handleQuery() {
  params.value.pageIndex = 1;
  getList();
}
function handleReset() {
  params.value.userName = "";
  params.value.pageIndex = 1;
  getList();
}
function handleSizeChange(size: number) {
  params.value.pageSize = size;
  params.value.pageIndex = 1;
  getList();
}
function handleCurrentChange(page: number) {
  params.value.pageIndex = page;
  getList();
}

const router = useRouter();
function handleToggleStatus(row: UserType) {
  const newStatus = row.status === 1 ? 0 : 1;
  const actionText = newStatus === 1 ? "启用" : "禁用";

  UserAPI.changeStatus(row.id)
    .then(() => {
      row.status = newStatus;
      ElMessage.success(`${actionText}成功`);
    })
    .catch(() => {
      ElMessage.error(`${actionText}失败`);
    });
}
function handleEdit(row: UserType) {
  router.push({ name: "AdminEditView", query: { id: row.id } });
}
function handleDelete(row: UserType) {
  ElMessageBox.confirm(`确定删除用户【${row.userName}】吗？`, "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(() => {
      loading.value = true;
      UserAPI.deleteUser(row.id)
        .then(() => {
          ElMessage.success("删除成功");
          // 如果当前页只有一条被删且不是第一页，自动回到上一页
          if (tableData.value.length === 1 && params.value.pageIndex > 1) {
            params.value.pageIndex -= 1;
          }
          getList();
        })
        .catch(() => {
          ElMessage.error("删除失败");
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      /* 用户取消 */
    });
}
function handleAdd() {
  router.push({ name: "AdminAddView" });
}

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.student {
  padding: 16px;
}
</style>
